import router from './router';
import { getCache } from '@/utils/session';
import getPageTitle from '@/utils/getPageTitle';
import NProgress from 'nprogress'; // progress bar
import 'nprogress/nprogress.css'; // progress bar style
import { message } from 'ant-design-vue';
import store from './store';
import { resetRouter } from '@/router';

NProgress.configure({ showSpinner: false }); // NProgress Configuration

router.beforeEach(async (to, from, next) => {
    NProgress.start();

    document.title = getPageTitle(to.meta.title);
    const isLogin = getCache('TOKEN');
    let tenant = getCache('tenant') || 'master';

    if (to.name == 'login') {
        next();
        NProgress.done();
    } else {
        if (!isLogin) {
            next(`/${tenant}/login`);
        } else {
            const userInfo = store.state.user.accountInfo || '';
            if (userInfo) {
                next();
                NProgress.done();
            } else {
                try {
                    await store.dispatch('user/getUserInfo');
                    let accountRoute = store.getters.baseRoute;
                    resetRouter();
                    console.log(accountRoute)
                    router.addRoutes(accountRoute)
                    next({ ...to, replace: true });
                    NProgress.done();

                } catch(err) {
                    // message.error('获取用户信息失败');
                    next(`/${tenant}/login`);
                    NProgress.done();
                }
            }
        }
    }
});

router.afterEach(() => {
    NProgress.done();
});
